<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { API_CONFIG } from '../../config/apiConfig';

// 定义菜单项类型
interface MenuItem {
  id: string;
  permission: string;
  name: string;
  parentId: string;
  childrenList?: MenuItem[];
}

const emit = defineEmits<{
  close: [];
  'permissions-updated': [];
}>();

// 角色列表
const roles = [
  { id: 2, name: '管理员' },
  { id: 3, name: '普通用户' },
  { id: 5, name: '毕业学员' }
];

const selectedRole = ref(roles[0].id);
const allMenus = ref<MenuItem[]>([]);
const selectedMenuIds = ref<string[]>([]);
const isLoading = ref(false);
const isSaving = ref(false);
const errorMessage = ref('');
const successMessage = ref('');

// 监听角色变化，获取对应角色的权限
watch(selectedRole, () => {
  fetchRolePermissions();
});

// 将扁平菜单数据转换为树形结构
const convertToTreeStructure = (menuList: MenuItem[]): MenuItem[] => {
  // 创建一个映射表，用于快速查找菜单项
  const menuMap: Record<string, MenuItem> = {};
  menuList.forEach(menu => {
    // 确保每个菜单项都有一个空的childrenList数组
    menuMap[menu.id] = { ...menu, childrenList: [] };
  });
  
  // 构建树形结构
  const treeMenus: MenuItem[] = [];
  menuList.forEach(menu => {
    const menuWithChildren = menuMap[menu.id];
    
    if (menu.parentId === "0") {
      // 这是一个父节点
      treeMenus.push(menuWithChildren);
    } else {
      // 这是一个子节点，将其添加到父节点的childrenList中
      const parentMenu = menuMap[menu.parentId];
      if (parentMenu) {
        // 确保父菜单的childrenList存在
        if (!parentMenu.childrenList) {
          parentMenu.childrenList = [];
        }
        // 安全地添加子菜单
        parentMenu.childrenList.push(menuWithChildren);
      } else {
        // 如果找不到父菜单，将其作为顶级菜单添加
        console.warn(`找不到菜单项 ${menu.id} 的父菜单 ${menu.parentId}，将其作为顶级菜单添加`);
        treeMenus.push(menuWithChildren);
      }
    }
  });
  
  return treeMenus;
};

// 获取所有菜单
const fetchAllMenus = async () => {
  isLoading.value = true;
  errorMessage.value = '';
  
  try {
    const response = await fetch(`${API_CONFIG.BASE_URL}/user/menu/all`, {
      method: 'GET',
      credentials: 'include'
    });
    
    const result = await response.json();
    
    if (result.code === '0') {
      // 将扁平数据转换为树形结构
      allMenus.value = convertToTreeStructure(result.data);
    } else {
      errorMessage.value = `获取菜单失败: ${result.msg}`;
    }
  } catch (error) {
    console.error('获取菜单失败:', error);
    errorMessage.value = '获取菜单失败，请检查网络连接';
  } finally {
    isLoading.value = false;
  }
};

// 获取角色已有权限
const fetchRolePermissions = async () => {
  if (!selectedRole.value) return;
  
  isLoading.value = true;
  errorMessage.value = '';
  
  try {
    const response = await fetch(`${API_CONFIG.BASE_URL}/user/menu/${selectedRole.value}`, {
      method: 'GET',
      credentials: 'include'
    });
    
    const result = await response.json();
    
    if (result.code === '0') {
      // 提取所有菜单ID
      selectedMenuIds.value = extractMenuIds(result.data);
    } else {
      errorMessage.value = `获取角色权限失败: ${result.msg}`;
    }
  } catch (error) {
    console.error('获取角色权限失败:', error);
    errorMessage.value = '获取角色权限失败，请检查网络连接';
  } finally {
    isLoading.value = false;
  }
};

// 递归提取菜单ID
const extractMenuIds = (menus: MenuItem[]): string[] => {
  const ids: string[] = [];
  
  const extract = (items: MenuItem[]) => {
    items.forEach(item => {
      ids.push(item.id);
      if (item.childrenList && item.childrenList.length > 0) {
        extract(item.childrenList);
      }
    });
  };
  
  extract(menus);
  return ids;
};

// 获取所有子节点ID
const getChildrenIds = (parentId: string, menuList: MenuItem[]): string[] => {
  const ids: string[] = [];
  const parent = findMenuById(parentId, menuList);
  
  if (parent && parent.childrenList) {
    parent.childrenList.forEach(child => {
      ids.push(child.id);
      // 如果子节点还有子节点，递归获取
      if (child.childrenList && child.childrenList.length > 0) {
        ids.push(...getChildrenIds(child.id, menuList));
      }
    });
  }
  
  return ids;
};

// 获取同级节点ID
const getSiblingIds = (menuId: string, parentId: string, menuList: MenuItem[]): string[] => {
  const parent = findMenuById(parentId, menuList);
  if (!parent || !parent.childrenList) return [];
  
  return parent.childrenList
    .filter(child => child.id !== menuId)
    .map(child => child.id);
};

// 处理菜单选择变化
const handleMenuChange = (menuId: string, checked: boolean) => {
  // 移除会话管理菜单必选的限制

  // 创建一个新的选中ID数组
  let newSelectedMenuIds = [...selectedMenuIds.value];
  
  // 查找当前菜单项及其父菜单
  const currentMenu = findMenuById(menuId, allMenus.value);
  const parentMenu = currentMenu && currentMenu.parentId !== "0" ? 
    findMenuById(currentMenu.parentId, allMenus.value) : null;

  if (checked) {
    // 选中当前菜单
    if (!newSelectedMenuIds.includes(menuId)) {
      newSelectedMenuIds.push(menuId);
    }
    
    // 如果是子节点被选中，确保父节点也被选中
    if (parentMenu && !newSelectedMenuIds.includes(parentMenu.id)) {
      newSelectedMenuIds.push(parentMenu.id);
    }
    
    // 如果是父节点被选中，选中所有子节点
    const childrenIds = getChildrenIds(menuId, allMenus.value);
    childrenIds.forEach(childId => {
      if (!newSelectedMenuIds.includes(childId)) {
        newSelectedMenuIds.push(childId);
      }
    });
  } else {
    // 取消选中当前菜单
    newSelectedMenuIds = newSelectedMenuIds.filter(id => id !== menuId);
    
    // 如果是父节点被取消选中，取消选中所有子节点
    const childrenIds = getChildrenIds(menuId, allMenus.value);
    newSelectedMenuIds = newSelectedMenuIds.filter(id => !childrenIds.includes(id));
    
    // 检查是否需要取消选中父节点（当所有子节点都未选中时）
    if (parentMenu) {
      const siblingIds = getSiblingIds(menuId, parentMenu.id, allMenus.value);
      const anySiblingSelected = siblingIds.some(id => newSelectedMenuIds.includes(id));
      
      if (!anySiblingSelected) {
        // 如果没有兄弟节点被选中，可以考虑取消选中父节点
        newSelectedMenuIds = newSelectedMenuIds.filter(id => id !== parentMenu.id);
      }
    }
  }
  
 
  
  // 更新选中状态
  selectedMenuIds.value = newSelectedMenuIds;
};

// 组件挂载时确保会话管理权限被选中
onMounted(() => {
  fetchAllMenus();
  fetchRolePermissions();
  
 
});



// 根据ID查找菜单项
const findMenuById = (id: string, menus: MenuItem[]): MenuItem | null => {
  for (const menu of menus) {
    if (menu.id === id) {
      return menu;
    }
    
    if (menu.childrenList) {
      const found = findMenuById(id, menu.childrenList);
      if (found) {
        return found;
      }
    }
  }
  
  return null;
};

// 保存角色权限
const handleSubmit = async () => {
  if (!selectedRole.value) return;
  
  isSaving.value = true;
  errorMessage.value = '';
  successMessage.value = '';
  
  try {
    const response = await fetch(`${API_CONFIG.BASE_URL}/user/role/${selectedRole.value}/menu`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      credentials: 'include',
      body: JSON.stringify({
        roleId: selectedRole.value,
        menuIds: selectedMenuIds.value.map(id => parseInt(id))
      })
    });
    
    const result = await response.json();
    
    if (result.code === '0') {
      successMessage.value = '权限设置成功';
      setTimeout(() => {
        emit('permissions-updated');
        emit('close');
      }, 1500);
    } else {
      errorMessage.value = `保存失败: ${result.msg}`;
    }
  } catch (error) {
    console.error('保存权限失败:', error);
    errorMessage.value = '保存权限失败，请检查网络连接';
  } finally {
    isSaving.value = false;
  }
};

// 注意：已在上方定义了onMounted钩子，此处不需要重复
</script>

<template>
  <div class="role-permission-form">
    <h2>角色权限管理</h2>
    
    <div v-if="isLoading" class="loading">
      加载中...
    </div>
    
    <form v-else @submit.prevent="handleSubmit">
      <div class="form-group">
        <label>选择角色</label>
        <select v-model="selectedRole" class="role-select">
          <option v-for="role in roles" :key="role.id" :value="role.id">
            {{ role.name }}
          </option>
        </select>
      </div>
      
      <div class="permissions-container">
        <h3>权限设置</h3>
        
        <div v-if="allMenus.length === 0" class="no-permissions">
          暂无可配置的权限
        </div>
        
        <div v-else class="menu-list">
          <div v-for="menu in allMenus" :key="menu.id" class="menu-item parent">
            <div class="menu-checkbox">
              <input 
                type="checkbox" 
                :id="`menu-${menu.id}`" 
                :checked="selectedMenuIds.includes(menu.id)"
                @change="e => handleMenuChange(menu.id, (e.target as HTMLInputElement).checked)"
              />
              <label :for="`menu-${menu.id}`">
                {{ menu.name }}
                
              </label>
            </div>
            
            <div v-if="menu.childrenList && menu.childrenList.length > 0" class="submenu-list">
              <div v-for="submenu in menu.childrenList" :key="submenu.id" class="menu-item child">
                <div class="menu-checkbox">
                  <input 
                    type="checkbox" 
                    :id="`menu-${submenu.id}`" 
                    :checked="selectedMenuIds.includes(submenu.id)"
                    @change="e => handleMenuChange(submenu.id, (e.target as HTMLInputElement).checked)"
                  />
                  <label :for="`menu-${submenu.id}`">{{ submenu.name }}</label>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>
      
      <div v-if="successMessage" class="success-message">
        {{ successMessage }}
      </div>
      
      <div class="form-actions">
        <button type="button" class="cancel-btn" @click="emit('close')">取消</button>
        <button type="submit" class="submit-btn" :disabled="isSaving">
          {{ isSaving ? '保存中...' : '保存' }}
        </button>
      </div>
    </form>
  </div>
</template>

<style scoped>
.role-permission-form {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

h2 {
  margin: 0 0 20px 0;
  font-size: 18px;
  font-weight: 600;
}

h3 {
  margin: 20px 0 10px 0;
  font-size: 16px;
  font-weight: 500;
}

.loading {
  text-align: center;
  padding: 20px;
  color: #6b7280;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #374151;
}

.role-select {
  width: 100%;
  padding: 8px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  font-size: 14px;
}

.permissions-container {
  margin-bottom: 20px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  padding: 15px;
  background-color: #f9fafb;
  max-height: calc(100vh - 300px);
  overflow-y: auto;
}

.no-permissions {
  text-align: center;
  padding: 20px;
  color: #6b7280;
}

.menu-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.menu-item {
  margin-bottom: 5px;
}

.menu-item.parent {
  margin-bottom: 15px;
}

.menu-checkbox {
  display: flex;
  align-items: center;
  gap: 8px;
}

.menu-checkbox input[type="checkbox"] {
  width: 16px;
  height: 16px;
}

.submenu-list {
  margin-left: 25px;
  margin-top: 8px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.error-message {
  color: #b91c1c;
  margin-bottom: 15px;
}

.success-message {
  color: #15803d;
  margin-bottom: 15px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.cancel-btn,
.submit-btn {
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
}

.cancel-btn {
  background-color: #f3f4f6;
  border: 1px solid #e5e7eb;
  color: #374151;
}

.submit-btn {
  background-color: #3b82f6;
  border: none;
  color: white;
}

.cancel-btn:hover {
  background-color: #e5e7eb;
}

.submit-btn:hover:not(:disabled) {
  background-color: #2563eb;
}

.submit-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 必选菜单项样式 */
.required-menu {
  color: #1f2937;
  font-weight: 600;
}

.required-tag {
  font-size: 12px;
  color: #ef4444;
  margin-left: 4px;
  background-color: #fee2e2;
  padding: 2px 6px;
  border-radius: 4px;
}

input[type="checkbox"]:disabled + label {
  cursor: not-allowed;
}
</style>